<template>
	<div class="goods-container">
		<!-- 操作按钮区域 -->
		<div class="action-bar">
			<t-button theme="primary" @click="addGoods">
				<template #icon>
					<span class="add-icon">+</span>
				</template>
				添加商品
			</t-button>
		</div>

		<!-- 商品卡片列表 -->
		<div class="goods-grid" v-loading="loading">
			<div
				v-for="item in goodsList"
				:key="item.id"
				class="goods-card"
				@click="viewDetail(item)"
			>
				<!-- 操作按钮区域 -->
				<div class="goods-actions">
					<t-button
						theme="primary"
						variant="text"
						size="small"
						@click.stop="editGoods(item)"
						class="action-btn edit-btn"
					>
						<template #icon>
							<t-icon name="edit" />
						</template>
					</t-button>
					<t-button
						theme="danger"
						variant="text"
						size="small"
						@click.stop="deleteGoods(item)"
						class="action-btn delete-btn"
					>
						<template #icon>
							<t-icon name="delete" />
						</template>
					</t-button>
				</div>

				<div class="goods-image">
					<img :src="item.image" :alt="item.name" />
				</div>
				<div class="goods-info">
					<h3 class="goods-name">{{ item.name }}</h3>
					<p class="goods-description">{{ item.description }}</p>
					<div class="goods-price">
						<span class="points">{{ item.price }}</span>
						<span class="points-text">积分</span>
					</div>
				</div>
			</div>
		</div>

		<!-- 分页组件 -->
		<div class="pagination">
			<t-pagination
				:current="pagination.current"
				:page-size="pagination.pageSize"
				:total="pagination.total"
				:show-jumper="true"
				:show-page-size="true"
				:page-size-options="[12, 24, 48, 96]"
				@change="onPageChange"
			/>
		</div>

		<!-- 商品抽屉 -->
		<goods-drawer
			v-model="goodsDrawerVisible"
			:goods-data="currentEditGoods"
			@success="handleGoodsDrawerSuccess"
		/>
	</div>
</template>

<script>
import GoodsDrawer from './goods-drawer.vue';
import { getGoodsPage, deleteGoods as deleteGoodsApi } from '@/api/goods';
import { DialogPlugin as TDialog } from 'tdesign-vue';

export default {
	name: 'Goods',
	components: {
		GoodsDrawer
	},
	data() {
		return {
			loading: false,
			goodsDrawerVisible: false,
			currentEditGoods: null,
			goodsList: [],
			pagination: {
				current: 1,
				pageSize: 12,
				total: 0,
				showJumper: true,
				showPageSize: true,
				pageSizeOptions: [12, 24, 48, 96],
			},
		};
	},
	mounted() {
		this.loadGoodsList();
	},
	methods: {
		// 加载商品列表
		async loadGoodsList() {
			this.loading = true;

			try {
				const params = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
				};

				const res = await getGoodsPage(params);

				// 根据实际返回的数据结构处理数据
				// 假设返回结构为: { data: { data: { data: [...], total: 100, page: 1, pageSize: 12 } } }
				if (res && res.data && res.data.data) {
					this.goodsList = Array.isArray(res.data.data.data) ? res.data.data.data : [];
					this.pagination.total = Number(res.data.data.total) || 0;
					// 可选：同步其他分页信息
					this.pagination.current = Number(res.data.data.page) || this.pagination.current;
					this.pagination.pageSize = Number(res.data.data.pageSize) || this.pagination.pageSize;
				} else {
					this.goodsList = [];
					this.pagination.total = 0;
				}
			} catch (error) {
				console.error('加载商品列表失败:', error);
				this.$message.error('加载商品列表失败');
				this.goodsList = [];
				this.pagination.total = 0;
			} finally {
				this.loading = false;
			}
		},

		// 分页变化处理
		onPageChange({current, pageSize}) {
			this.pagination.current = current;

			if (pageSize !== this.pagination.pageSize) {
				this.pagination.current = 1;
			}

			this.pagination.pageSize = pageSize;

			this.loadGoodsList();
		},

		viewDetail(item) {
			this.currentEditGoods = item;
			this.goodsDrawerVisible = true;
		},

		addGoods() {
			this.currentEditGoods = null;
			this.goodsDrawerVisible = true;
		},

		// 编辑商品
		editGoods(item) {
			this.currentEditGoods = item;
			this.goodsDrawerVisible = true;
		},

		// 删除商品
		async deleteGoods(item) {
			// 基本验证
			if (!item || !item.id) {
				this.$message.error('无效的数据');
				return;
			}

			const confirmMessage = `确定要删除商品"${item.name}"吗？`;
			const warningMessage = '删除后不可恢复。';

			try {
				// 使用TDesign推荐的确认对话框
				const confirmDialog = await new Promise((resolve) => {
					const instance = TDialog.confirm({
						header: '确认删除',
						body: () => {
							return this.$createElement(
								'div',
								{
									style: {
										lineHeight: '1.6',
									},
								},
								[
									this.$createElement(
										'p',
										{
											style: {
												margin: '0 0 8px 0',
												color: '#333',
											},
										},
										confirmMessage
									),
									this.$createElement(
										'p',
										{
											style: {
												margin: '0',
												color: '#ff4d4f',
												fontWeight: '500',
											},
										},
										warningMessage
									),
								]
							);
						},
						confirmBtn: {
							content: '确定删除',
							theme: 'danger',
							loading: false,
						},
						cancelBtn: '取消',
						onConfirm: () => {
							resolve(instance);
						},
						onCancel: () => {
							resolve(null);
						},
					});
				});

				// 用户取消删除
				if (!confirmDialog) {
					return;
				}

				// 显示删除按钮加载状态
				confirmDialog.update({
					confirmBtn: {
						content: '删除中...',
						theme: 'danger',
						loading: true,
					},
				});

				// 调用删除API
				await deleteGoodsApi(item.id);

				confirmDialog.hide();
				this.$message.success('删除成功');
				// 重新加载商品列表
				this.loadGoodsList();
			} catch (error) {
				console.error('删除商品失败:', error);

				// 根据错误类型显示不同的错误信息
				let errorMessage = '删除失败';
				if (error.message) {
					errorMessage = error.message;
				} else if (error.response?.data?.message) {
					errorMessage = error.response.data.message;
				} else if (error.response?.status === 403) {
					errorMessage = '没有权限删除此商品';
				} else if (error.response?.status === 409) {
					errorMessage = '该商品正在被使用，无法删除';
				} else if (error.code === 'NETWORK_ERROR') {
					errorMessage = '网络连接失败，请检查网络后重试';
				}

				this.$message.error(errorMessage);

				// 如果对话框还存在，隐藏它
				if (confirmDialog && typeof confirmDialog.hide === 'function') {
					confirmDialog.hide();
				}
			}
		},

		handleGoodsDrawerSuccess(formData) {
			console.log('商品操作成功:', formData);
			// 重新加载商品列表
			this.loadGoodsList();
		}
	}
};
</script>

<style lang="less" scoped>
.goods-container {
	width: 100%;
	height: calc(100vh - 55px - 28px);
	overflow-y: auto;
	box-sizing: border-box;
	&::-webkit-scrollbar {
		width: 0;
		display: none;
	}
}

.action-bar {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	margin-bottom: 14px;
}

.add-icon {
	font-size: 16px;
	font-weight: bold;
	line-height: 1;
}

.page-title {
	text-align: center;
	color: #333;
	margin-bottom: 30px;
	font-size: 28px;
	font-weight: 600;
}

.goods-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 14px;
	margin-bottom: 14px;
}

.goods-card {
	background: #fff;
	border-radius: 12px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	overflow: hidden;
	transition: all 0.3s ease;
	cursor: pointer;
	position: relative;

	&:hover {
		transform: translateY(-5px);
		box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);

		.goods-actions {
			opacity: 1;
			visibility: visible;
		}
	}
}

.goods-actions {
	position: absolute;
	top: 8px;
	right: 8px;
	display: flex;
	gap: 4px;
	opacity: 0;
	visibility: hidden;
	transition: all 0.3s ease;
	z-index: 10;

	.action-btn {
		width: 32px;
		height: 32px;
		border-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(4px);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

		&:hover {
			transform: scale(1.05);
		}

		&.edit-btn {
			color: #0052d9;

			&:hover {
				background: rgba(0, 82, 217, 0.1);
			}
		}

		&.delete-btn {
			color: #e34d59;

			&:hover {
				background: rgba(227, 77, 89, 0.1);
			}
		}
	}
}

.goods-image {
	width: 100%;
	height: 200px;
	overflow: hidden;

	img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transition: transform 0.3s ease;
	}

	&:hover img {
		transform: scale(1.05);
	}
}

.goods-info {
	padding: 16px;
}

.goods-name {
	font-size: 16px;
	font-weight: 600;
	color: #333;
	margin: 0 0 8px 0;
	line-height: 1.4;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-description {
	font-size: 14px;
	color: #666;
	line-height: 1.5;
	margin: 0 0 12px 0;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-price {
	display: flex;
	align-items: center;
	gap: 4px;
}

.points {
	font-size: 20px;
	font-weight: 700;
	color: #ff6b35;
}

.points-text {
	font-size: 14px;
	color: #ff6b35;
	font-weight: 500;
}

.pagination {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 14px;
	margin-bottom: 28px;
}

// 响应式设计
@media (max-width: 992px) {
	.goods-grid {
		grid-template-columns: repeat(2, 1fr);
	}
}

@media (max-width: 576px) {
	.goods-container {
		padding: 15px;
	}

	.goods-grid {
		grid-template-columns: 1fr;
		gap: 15px;
	}

	.page-title {
		font-size: 24px;
		margin-bottom: 20px;
	}

	// 移动端始终显示操作按钮
	.goods-actions {
		opacity: 1;
		visibility: visible;
	}
}
</style>